using System;
using System.IO;
using System.Threading.Tasks;
using Newtonsoft.Json;
using WPFNote.Utilities.Http;
using WPFNote.Utilities.Common;
using WPFNote.Utilities.ReturnJson;

namespace WPFNote.Services
{
    public class Login
    {
        private IDal.IUsers _users;
        public Login(IDal.IUsers users)
        {
            _users = users;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async Task<(bool, string)> Auth(string userName, string password)
        {
            var enPwd = EncryptionHelper.Md5(password);
            var user = await _users.SelectAsync(new Models.UsersSch() { UserName = userName });
            if (user == null)
            {
                // 用户不存在，进行注册
                user = new Models.Users()
                {
                    UserName = userName,
                    Password = enPwd
                };
                var id = await _users.InsertReturnIdAsync(user);
                if (id <= 0)
                {
                    return (false, "注册失败");
                }
                user.Id = id;
            }
            else if (!user.Password.Equals(enPwd))
            {
                return (false, "登录失败，密码错误");
            }
            var userJson = JsonConvert.SerializeObject(user);
            var enUserInfo = EncryptionHelper.EncodeBase64(userJson);
            //保存到本地
            new BinFileHelper().Write(AppSession.UserInfoPath, enUserInfo);
            AppSession.UserInfo = user;
            return (true, "登录成功");
        }
    }
}